import 'dart:async';
import 'dart:convert';

import 'package:elephant_fish/TRTCLiveRoomDemo/model/TRTCLiveRoom.dart';
import 'package:elephant_fish/TRTCLiveRoomDemo/model/TRTCLiveRoomDef.dart';
import 'package:elephant_fish/TRTCLiveRoomDemo/model/TRTCLiveRoomDelegate.dart';
import 'package:elephant_fish/TRTCLiveRoomDemo/ui/base/FavoriteAnimation.dart';
import 'package:elephant_fish/TRTCLiveRoomDemo/ui/base/FilterSetting.dart';
import 'package:elephant_fish/TRTCLiveRoomDemo/ui/base/LiveImgButton.dart';
import 'package:elephant_fish/TRTCLiveRoomDemo/ui/base/LiveMessageList.dart';
import 'package:elephant_fish/TRTCLiveRoomDemo/ui/base/LiveTextButton.dart';
import 'package:elephant_fish/TRTCLiveRoomDemo/ui/base/MusicSetting.dart';
import 'package:elephant_fish/TRTCLiveRoomDemo/ui/base/PKUserList.dart';
import 'package:elephant_fish/TRTCLiveRoomDemo/ui/base/PopUpMessageList.dart';
import 'package:elephant_fish/TRTCLiveRoomDemo/ui/base/SubVideoList.dart';
import 'package:elephant_fish/base/YunApiHelper.dart';
import 'package:elephant_fish/debug/GenerateTestUserSig.dart';
import 'package:elephant_fish/http/core/hi_net.dart';
import 'package:elephant_fish/http/request/attention_anchor_request.dart';
import 'package:elephant_fish/http/request/attention_room_request.dart';
import 'package:elephant_fish/http/request/base_request.dart';
import 'package:elephant_fish/http/request/end_broadcast.dart';
import 'package:elephant_fish/http/request/get_room_anchor_request.dart';
import 'package:elephant_fish/http/request/live_drop_out_request.dart';
import 'package:elephant_fish/http/request/room_leaderboard_request.dart';
import 'package:elephant_fish/model/gift_entity.dart';
import 'package:elephant_fish/model/leaderboard_entity.dart';
import 'package:elephant_fish/model/user_info_entity.dart';
import 'package:elephant_fish/page/login_page.dart';
import 'package:elephant_fish/page/wallet_page.dart';
import 'package:elephant_fish/util/Alert.dart';
import 'package:elephant_fish/util/TxUtils.dart';
import 'package:elephant_fish/util/size_util.dart';
import 'package:elephant_fish/widget/broast_gift.dart';
import 'package:elephant_fish/widget/gift_list.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:location/location.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:tencent_im_sdk_plugin/manager/v2_tim_message_manager.dart';
import 'package:tencent_trtc_cloud/trtc_cloud_def.dart';
import 'package:tencent_trtc_cloud/trtc_cloud_video_view.dart';
import 'package:tencent_trtc_cloud/tx_audio_effect_manager.dart';
import 'package:tencent_trtc_cloud/tx_beauty_manager.dart';

class LiveRoomPage extends StatefulWidget {
  final Map arguments;

  const LiveRoomPage({Key key, this.isAdmin = false, this.arguments})
      : super(key: key);
  final bool isAdmin;

  @override
  _LiveRoomPageState createState() => _LiveRoomPageState();
}

List<String> giftList = [];
TRTCLiveRoom trtcLiveCloud;

class _LiveRoomPageState extends State<LiveRoomPage> {
  V2TIMMessageManager v2timMessageManager;
  TXBeautyManager beautyManager;
  TXAudioEffectManager audioEffectManager;
  UserInfoEntity userInfoEntity;
  UserInfoEntity userInfoEntity1;
  UserInfoEntity userInfoEntity2;
  bool isShowFilterSetting = false;
  bool isShowMusicSetting = false;
  bool isShowPkUserList = false;
  bool isShowComment = false;
  bool isFrontCamera = true;
  bool isBarrageON = true;
  bool isBarrageSliderOn = false;
  bool isShield = false;
  int _onLineUserCount = 0;
  String _currenRoomName = "";
  String _currentOwnerId = "";
  bool isOwerAvailable = true;
  int _currentRoomId = 0;
  Map<String, bool> _smallVideoUserId = {};
  String _currentLoginUser = '';
  ScrollController _scrollController = ScrollController();
  bool isJoinAnchor = false;
  bool isFollowed = false;
  bool isPKing = false;
  String pkUserId = "";
  List<RoomInfo> _pkUserList = [];
  List<List<MessageColor>> _messageLogList = [];
  String musicTips = "";
  List<String> _popupMessageList = [];
  List<String> _popupGiftList = [];
  bool isFavoriteVisiable = false;
  List<LeaderBorardEntity> leaderList = [];
  TextEditingController inputController = new TextEditingController();
  final inputFocusNode = FocusNode();

  @override
  void initState() {
    initTrtc();
    super.initState();
    initRoomInfo();
    // getLocation();
  }

  initTrtc() async {
    trtcLiveCloud = await TRTCLiveRoom.sharedInstance();
    beautyManager = trtcLiveCloud.getBeautyManager();
    audioEffectManager = trtcLiveCloud.getAudioEffectManager();
    trtcLiveCloud.registerListener(onListenerFunc);
  }

  initRoomInfo() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    userInfoEntity =
        UserInfoEntity.fromJson(jsonDecode(prefs.getString('USERINFO')));
    userInfoEntity2 = userInfoEntity;
    String currLoginUserId = await TxUtils.getLoginUserId();
    _currentLoginUser = currLoginUserId;
    Map arguments = ModalRoute.of(context).settings.arguments as Map;
    int _tpmCurrentRoomId = int.tryParse(arguments['roomId'].toString());
    _currentOwnerId = arguments['ownerId'].toString();
    _currentRoomId = _tpmCurrentRoomId;
    getRoomAnchor();
    getRoomLeaderBoard();
    bool isNeedCreateRoom = false;
    if (arguments.containsKey('isNeedCreateRoom')) {
      isNeedCreateRoom = arguments['isNeedCreateRoom'] as bool;
    }
    await trtcLiveCloud.login(
      GenerateTestUserSig.sdkAppId,
      currLoginUserId,
      GenerateTestUserSig.genTestSig(currLoginUserId),
      TRTCLiveRoomConfig(useCDNFirst: false),
    );
    await trtcLiveCloud.setSelfProfile(
        userInfoEntity.nickname == '' ? '暂未设置名称' : userInfoEntity.nickname,
        userInfoEntity.avatar == ''
            ? TxUtils.getRandoAvatarUrl()
            : userInfoEntity.avatar);
    if (isNeedCreateRoom) {
      await createRoom(
          _tpmCurrentRoomId,
          RoomParam(
            roomName: arguments['roomName'].toString(),
            quality: arguments['isStandardQuality']
                ? null
                : TRTCCloudDef.TRTC_AUDIO_QUALITY_MUSIC,
            //头像连接
            coverUrl: userInfoEntity == null
                ? 'https://imgcache.qq.com/operation/dianshi/other/5.ca48acfebc4dfb68c6c463c9f33e60cb8d7c9565.png'
                : userInfoEntity.avatar == ""
                    ? 'https://imgcache.qq.com/operation/dianshi/other/5.ca48acfebc4dfb68c6c463c9f33e60cb8d7c9565.png'
                    : "http://119.28.131.94:82" + userInfoEntity.avatar,
          ));
    } else {
      ActionCallback _actionCallback =
          await trtcLiveCloud.enterRoom(_tpmCurrentRoomId);
      if (_actionCallback.code != 0) {
        TxUtils.showToast("进房失败" + _actionCallback.desc, context);
        Navigator.pushNamed(context, '/index');
      }
    }
    getPKList(currLoginUserId, null);
    UserListCallback memberListCallback =
        await trtcLiveCloud.getRoomMemberList(0);
    UserListCallback anchorListCallback = await trtcLiveCloud.getAnchorList();
    _currenRoomName = arguments['roomName'].toString();

    Future.delayed(
      Duration(microseconds: 30),
      () {
        FilterSettingWidget.initBeautyValue.forEach((curBeauty, value) {
          this.onBeautyValueChange(curBeauty, value);
        });
        safeSetState(
          () {
            _currentRoomId = _tpmCurrentRoomId;
            _currenRoomName = arguments['roomName'].toString();
            if (memberListCallback.list != null) {
              _onLineUserCount = memberListCallback.list.length;
            }
            if (anchorListCallback.list != null) {
              anchorListCallback.list.forEach((element) {
                if (element.userId != _currentOwnerId) {
                  _smallVideoUserId[element.userId] = true;
                }
              });
            }
          },
        );
      },
    );
  }

  getPKList(currLoginUserId, Function callBack) async {
    if (widget.isAdmin) {
      var roomIdls = await YunApiHelper.getRoomList(roomType: 'liveRoom');

      RoomInfoCallback resp = await trtcLiveCloud.getRoomInfos(roomIdls);
      if (resp.code == 0 && resp.list != null) {
        safeSetState(() {
          _pkUserList = resp.list.where((element) {
            if (element.ownerId == currLoginUserId) return false;
            return true;
          }).toList();
          if (callBack != null) callBack();
        });
      }
    }
  }

  createRoom(roomId, RoomParam roomParam) async {
    ActionCallback actionCallback =
        await trtcLiveCloud.createRoom(roomId, roomParam);
    if (actionCallback.code == 0) {
      await YunApiHelper.createRoom(roomId.toString(), roomType: "liveRoom");
      await trtcLiveCloud.startPublish("");
    } else {
      showErrorToast("创建房间失败" + actionCallback.desc, stopAndGoIndex);
    }
    return await trtcLiveCloud.startPublish("");
  }

  @override
  void dispose() async {
    try {
      if (inputFocusNode.hasFocus) inputFocusNode.unfocus();
      super.dispose();
      await trtcLiveCloud.stopPublish();
      await trtcLiveCloud.stopCameraPreview();
      trtcLiveCloud.unRegisterListener(onListenerFunc);
      v2timMessageManager.removeAdvancedMsgListener();
    } catch (ex) {} finally {}
  }

  onListenerFunc(type, params) {
    switch (type) {
      case TRTCLiveRoomDelegate.onRecvRoomCustomMsg:
        {
          String command = params["command"].toString();
          if ('like' == command) {
            addMessageLog([
              MessageColor("来自 ", null),
              MessageColor(
                  params['user']['userName'].toString(), Color(0xFF3074FD)),
              MessageColor(" 的点赞", null)
            ]);
            print(params['userName']);
          } else if ('slider' == command) {
            safeSetState(() {
              _popupMessageList.add(params["message"].toString());
            });
          } else if ('gift' == command) {
            setState(() {
              const timeout = const Duration(seconds: 5);
              Timer(timeout, () {
                setState(() {
                  _popupGiftList.clear();
                });
              });
              _popupGiftList.add(params["message"].toString());
              setState(() {
                userInfoEntity2.userId = params['user']['userId'].toString();
                userInfoEntity2.nickname =
                    params['user']['userName'].toString();
                userInfoEntity2.avatar =
                    params['user']['userAvatar'].toString();
                getRoomLeaderBoard();
              });
              if (_popupGiftList.length > 3) {
                _popupGiftList.removeAt(0);
              }
            });
          }
        }
        break;
      case TRTCLiveRoomDelegate.onRoomDestroy:
        showErrorToast("房间已经被销毁", stopAndGoIndex);
        break;
      case TRTCLiveRoomDelegate.onKickedOffline:
        showErrorToast("你已在其他地方登陆了", stopAndGoIndex);
        break;
      case TRTCLiveRoomDelegate.onRecvRoomTextMsg:
        addMessageLog([
          MessageColor(params["userName"].toString(), Color(0xFFFCAF41)),
          MessageColor(": " + params["message"].toString(), null)
        ]);
        break;
      case TRTCLiveRoomDelegate.onUserVideoAvailable:
        onUserVideoAvailableHandle(params);
        break;

      case TRTCLiveRoomDelegate.onAnchorExit:
        {
          safeSetState(() {
            if (_smallVideoUserId.containsKey(params.toString()))
              _smallVideoUserId.remove(params.toString());
          });
          addMessageLog([
            MessageColor("主播 ", null),
            MessageColor(params["userName"].toString(), Color(0xFF3CCFA5)),
            MessageColor(" 离开房间", null)
          ]);
        }
        break;
      case TRTCLiveRoomDelegate.onAnchorEnter:
        {
          addMessageLog([
            MessageColor("欢迎主播 ", null),
            MessageColor(params['userName'].toString(), Color(0xFFFF8607)),
            MessageColor(" 进入房间", null)
          ]);
          safeSetState(() {
            pkUserId = params.toString();
            if (_currentOwnerId != params.toString()) {
              _smallVideoUserId[params.toString()] = true;
            }
          });
        }
        break;
      case TRTCLiveRoomDelegate.onAudienceEnter:
        {
          safeSetState(() {
            _onLineUserCount = _onLineUserCount + 1;
          });
          addMessageLog([
            MessageColor("欢迎 ", null),
            MessageColor(params["userName"].toString(), Color(0xFFF7AF97)),
            MessageColor(" 进入房间", null)
          ]);
        }
        break;
      case TRTCLiveRoomDelegate.onAudienceExit:
        {
          safeSetState(() {
            _onLineUserCount = _onLineUserCount - 1;
          });
          safeSetState(() {
            if (_smallVideoUserId.containsKey(params["userId"]))
              _smallVideoUserId.remove(params["userId"]);
          });
          addMessageLog([
            MessageColor(params["userName"].toString(), Color(0xFF3CCFA5)),
            MessageColor(" 离开房间", null)
          ]);
        }
        break;

      case TRTCLiveRoomDelegate.onRequestJoinAnchor:
        onRequestJoinAnchorHandle(params);
        break;
      case TRTCLiveRoomDelegate.onInvitationTimeout:
        {
          safeSetState(() {
            isJoinAnchor = false;
          });
          showErrorToast("申请超时", null);
        }
        break;
      case TRTCLiveRoomDelegate.onAnchorRejected:
        {
          safeSetState(() {
            isJoinAnchor = false;
          });
          showErrorToast("主播拒绝了你的申请", null);
        }
        break;
      case TRTCLiveRoomDelegate.onKickoutJoinAnchor:
        {
          safeSetState(() {
            isJoinAnchor = false;
            if (_smallVideoUserId.containsKey(_currentLoginUser)) {
              _smallVideoUserId.remove(_currentLoginUser);
            }
          });
          trtcLiveCloud.stopPublish();
          showErrorToast("你被管理员踢下主播", null);
        }
        break;
      case TRTCLiveRoomDelegate.onAnchorAccepted:
        onAnchorAcceptedHandle(params);
        break;

      case TRTCLiveRoomDelegate.onRoomPKRejected:
        {
          safeSetState(() {
            isPKing = false;
            pkUserId = '';
          });
          showErrorToast("主播拒绝跨房Pk请求", null);
        }
        break;
      case TRTCLiveRoomDelegate.onRoomPKAccepted:
        {
          addMessageLog([
            MessageColor(params["userName"].toString(), Color(0xFFFCAF41)),
            MessageColor(" 主播接受跨房Pk请求", null)
          ]);
          safeSetState(() {
            isPKing = true;
          });
        }
        break;
      case TRTCLiveRoomDelegate.onRequestRoomPK:
        {
          onRequestRoomPKHandle(params);
        }
        break;
      case TRTCLiveRoomDelegate.onQuitRoomPK:
        {
          safeSetState(() {
            isPKing = false;
            pkUserId = '';
          });
          showErrorToast("断开跨房 PK ", () {});
        }
        break;
    }
  }

  showErrorToast(String message, Function callback) {
    TxUtils.showErrorToast(message, context);
    if (callback != null) {
      Future.delayed(Duration(seconds: 2), () {
        callback();
      });
    }
  }

  //主播同意观众的连麦请求
  onAnchorAcceptedHandle(params) async {
    String userId = params["userId"].toString();
    safeSetState(() {
      isJoinAnchor = true;
      _smallVideoUserId[_currentLoginUser] = true;
    });
    await trtcLiveCloud.startPublish("");
    addMessageLog([
      MessageColor("主播同意 ", null),
      MessageColor(params['userName'], Color(0xFF3074FD)),
      MessageColor(" 连麦请求", null)
    ]);
  }

  ///发起PK
  onRequestRoomPKHandle(params) {
    showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text((params["userName"] == null
                  ? params["userId"].toString()
                  : params["userName"].toString()) +
              ' 发起PK请求'),
          actions: <Widget>[
            // ignore: deprecated_member_use
            FlatButton(
              child: Text("取消"),
              onPressed: () async {
                await trtcLiveCloud.responseRoomPK(
                    params["userId"].toString(), false);
                Navigator.pop(context);
              }, // 关闭对话框
            ),
            // ignore: deprecated_member_use
            FlatButton(
              child: Text("确定"),
              onPressed: () async {
                //关闭对话框并返回true
                await trtcLiveCloud.responseRoomPK(
                    params["userId"].toString(), true);
                safeSetState(() {
                  isPKing = true;
                });
                Navigator.pop(context);
              },
            ),
          ],
        );
      },
    );
  }

  onUserVideoAvailableHandle(param) {
    String userId = param['userId'];
    bool available = param['available'] as bool;
    // 根据状态对视频进行开启和关闭
    if (_currentOwnerId == userId) {
      setState(() {
        isOwerAvailable = available;
      });
    }
  }

  onRequestJoinAnchorHandle(params) {
    showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text((params["userName"] == null
                  ? params["userId"].toString()
                  : params["userName"].toString()) +
              ' 发起连麦请求'),
          actions: <Widget>[
            // ignore: deprecated_member_use
            FlatButton(
              child: Text("取消"),
              onPressed: () async {
                await trtcLiveCloud.responseJoinAnchor(
                    params["userId"].toString(), false);
                Navigator.pop(context);
              }, // 关闭对话框
            ),
            // ignore: deprecated_member_use
            FlatButton(
              child: Text("确定"),
              onPressed: () async {
                //关闭对话框并返回true
                await trtcLiveCloud.responseJoinAnchor(
                    params["userId"].toString(), true);
                Navigator.pop(context);
              },
            ),
          ],
        );
      },
    );
  }

  addMessageLog(List<MessageColor> logInfos) {
    safeSetState(() {
      _messageLogList.add(logInfos);
    });
  }

  //切换摄像头
  onCameraSwitchTap() {
    safeSetState(() {
      isFrontCamera = !isFrontCamera;
      trtcLiveCloud.switchCamera(isFrontCamera);
    });
  }

  onBeautyValueChange(String curBeauty, double value) {
    if (curBeauty == 'smooth' || curBeauty == 'nature' || curBeauty == 'pitu') {
      if ('smooth' == curBeauty) {
        beautyManager.setBeautyStyle(TRTCCloudDef.TRTC_BEAUTY_STYLE_SMOOTH);
      } else if ('nature' == curBeauty) {
        beautyManager.setBeautyStyle(TRTCCloudDef.TRTC_BEAUTY_STYLE_NATURE);
      } else if ('pitu' == curBeauty) {
        beautyManager.setBeautyStyle(TRTCCloudDef.TRTC_BEAUTY_STYLE_PITU);
      }
      beautyManager.setBeautyLevel(value.round());
    } else if (curBeauty == 'whitening') {
      beautyManager.setWhitenessLevel(value.round());
    } else if (curBeauty == 'ruddy') {
      beautyManager.setRuddyLevel(value.round());
    }
  }

  safeSetState(callBack) {
    setState(() {
      if (mounted) {
        callBack();
      }
    });
  }

  //滤镜
  onFilterSettingTap() {
    safeSetState(() {
      isShowFilterSetting = true;
      if (isShowFilterSetting) {
        showModalBottomSheet<void>(
          context: context,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(20),
              topRight: Radius.circular(20),
            ),
          ),
          builder: (BuildContext context) {
            return FilterSettingWidget(
              onChanged: onBeautyValueChange,
              onClose: () {
                safeSetState(() {
                  isShowFilterSetting = false;
                });
                Navigator.of(context).pop(true);
              },
            );
          },
        );
      }
    });
  }

  showQuitRoomPK() async {
    showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text("确定退出PK"),
          actions: <Widget>[
            // ignore: deprecated_member_use
            FlatButton(
              child: Text("取消"),
              onPressed: () async {
                Navigator.pop(context);
              }, // 关闭对话框
            ),
            // ignore: deprecated_member_use
            FlatButton(
              child: Text("确定"),
              onPressed: () async {
                await trtcLiveCloud.quitRoomPK();
                safeSetState(() {
                  isPKing = false;
                  pkUserId = '';
                });
                Navigator.pop(context);
              },
            ),
          ],
        );
      },
    );
  }

  stopAndGoIndex() async {
    try {
      await trtcLiveCloud.stopPublish();
      trtcLiveCloud.unRegisterListener(onListenerFunc);
      // if (widget.isAdmin) {
      //   await trtcLiveCloud.destroyRoom();
      //   await YunApiHelper.destroyRoom(_currentRoomId.toString(),
      //       roomType: 'liveRoom');
      // } else {
      //   await trtcLiveCloud.exitRoom();
      // }
      await trtcLiveCloud.exitRoom();
    } catch (ex) {} finally {
      if (mounted) {
        // Navigator.pushReplacementNamed(
        //   context,
        //   "/liveRoom/list",
        // );
        Navigator.pushNamed(context, '/index');
      }
    }
  }

  onCloseRoomTap() async {
    if (isPKing) {
      showQuitRoomPK();
      return;
    }
    if (widget.isAdmin) {
      endBroadcast();
    } else {
      liveDropOut();
    }
  }

  onCommentTap() {
    safeSetState(() {
      isShowComment = true;
    });
  }

  ///礼物分类背包
  onGiftSettingTap() {
    safeSetState(() {
      isShowMusicSetting = true;
      showModalBottomSheet(
          context: context,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(20),
              topRight: Radius.circular(20),
            ),
          ),
          builder: (BuildContext context) {
            return Container(
              child: BroastGift(roomId: _currentRoomId, isShield: isShield,userId: userInfoEntity1.userId1,),
            );
          }).then((_) => safeSetState(() {
            getRoomLeaderBoard();
            _popupGiftList = giftList;
            var timeout = Duration(seconds: 5);
            Timer(timeout, () {
              setState(() {
                _popupGiftList.clear();
              });
            });
          }));
    });
  }

  ///头像点击弹窗
  onAvatarSettingTap() {
    safeSetState(() {
      showModalBottomSheet(
          context: context,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(20),
              topRight: Radius.circular(20),
            ),
          ),
          builder: (BuildContext context) {
            return Container(
              height: SizeUtil.px(666),
              child: Column(
                children: [
                  Stack(
                    children: [
                      Align(
                        alignment: Alignment.topLeft,
                        child: Padding(
                          padding: EdgeInsets.only(
                              left: SizeUtil.px(34), top: SizeUtil.px(23)),
                          child: Text(
                            '举报',
                            style: TextStyle(
                                color: Color(0xffbebebe),
                                fontSize: SizeUtil.px(26)),
                          ),
                        ),
                      ),
                      Align(
                        alignment: Alignment.topCenter,
                        child: CircleAvatar(
                          radius: 32,
                          backgroundImage: NetworkImage(
                            userInfoEntity1 == null
                                ? 'https://imgcache.qq.com/operation/dianshi/other/5.ca48acfebc4dfb68c6c463c9f33e60cb8d7c9565.png'
                                : userInfoEntity1.avatar == ""
                                    ? 'https://imgcache.qq.com/operation/dianshi/other/5.ca48acfebc4dfb68c6c463c9f33e60cb8d7c9565.png'
                                    : "http://119.28.131.94:82" +
                                        userInfoEntity1.avatar,
                          ),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(
                    height: SizeUtil.px(11),
                  ),
                  Text(
                    userInfoEntity1 == null
                        ? '今天吃什么'
                        : userInfoEntity1.nickname == ""
                            ? '今天吃什么'
                            : userInfoEntity1.nickname,
                    style: TextStyle(
                        color: Color(0xff0c0c0c), fontSize: SizeUtil.px(32)),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(
                        Icons.copy,
                        color: Color(0xff595959),
                        size: SizeUtil.px(18),
                      ),
                      SizedBox(
                        width: SizeUtil.px(4),
                      ),
                      Text(
                        userInfoEntity1 == null
                            ? 'ID:123456'
                            : userInfoEntity1.idNumber == ""
                                ? 'ID:123456'
                                : 'ID:' + userInfoEntity1.idNumber,
                        style: TextStyle(
                            color: Color(0xff595959),
                            fontSize: SizeUtil.px(22)),
                      ),
                      SizedBox(
                        width: SizeUtil.px(48),
                      ),
                      Icon(
                        Icons.location_on_outlined,
                        color: Color(0xff595959),
                        size: SizeUtil.px(18),
                      ),
                      SizedBox(
                        width: SizeUtil.px(4),
                      ),
                      Text(
                        userInfoEntity1 == null
                            ? '好像在火星'
                            : userInfoEntity1.city == ""
                                ? '好像在火星'
                                : userInfoEntity1.city,
                        style: TextStyle(
                            color: Color(0xff595959),
                            fontSize: SizeUtil.px(22)),
                      ),
                    ],
                  ),
                  SizedBox(
                    height: SizeUtil.px(36),
                  ),
                  Text(
                    userInfoEntity1 == null
                        ? '这家伙很懒，什么都没留下'
                        : userInfoEntity1.signature == ""
                            ? '这家伙很懒，什么都没留下'
                            : userInfoEntity1.signature,
                    style: TextStyle(
                        color: Color(0xff818181), fontSize: SizeUtil.px(19)),
                  ),
                  SizedBox(
                    height: SizeUtil.px(18),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Container(
                        width: SizeUtil.px(208),
                        height: SizeUtil.px(89),
                        decoration: BoxDecoration(
                          borderRadius:
                              BorderRadius.all(Radius.circular(SizeUtil.px(9))),
                          gradient: LinearGradient(
                            begin: Alignment.centerLeft,
                            end: Alignment.centerRight,
                            colors: [Color(0xfffed32e), Color(0xfff79d2b)],
                          ),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              '财富等级',
                              style: TextStyle(
                                  color: Color(0xfff3f3f3),
                                  fontSize: SizeUtil.px(26)),
                            )
                          ],
                        ),
                      ),
                      SizedBox(
                        width: SizeUtil.px(19),
                      ),
                      Container(
                        width: SizeUtil.px(208),
                        height: SizeUtil.px(89),
                        decoration: BoxDecoration(
                          borderRadius:
                              BorderRadius.all(Radius.circular(SizeUtil.px(9))),
                          gradient: LinearGradient(
                            begin: Alignment.centerLeft,
                            end: Alignment.centerRight,
                            colors: [Color(0xffff1266), Color(0xfffe7170)],
                          ),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              '主播等级',
                              style: TextStyle(
                                  color: Color(0xfff3f3f3),
                                  fontSize: SizeUtil.px(26)),
                            )
                          ],
                        ),
                      ),
                      SizedBox(
                        width: SizeUtil.px(19),
                      ),
                      Container(
                        width: SizeUtil.px(208),
                        height: SizeUtil.px(89),
                        decoration: BoxDecoration(
                          borderRadius:
                              BorderRadius.all(Radius.circular(SizeUtil.px(9))),
                          color: Color(0xffa5a5a5),
                        ),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Text(
                              '平民',
                              style: TextStyle(
                                  color: Color(0xfff3f3f3),
                                  fontSize: SizeUtil.px(26)),
                            )
                          ],
                        ),
                      ),
                    ],
                  ),
                  SizedBox(
                    height: SizeUtil.px(58),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Column(
                        children: [
                          Text(
                            userInfoEntity1 == null
                                ? '0'
                                : userInfoEntity1.attentions == null
                                    ? '0'
                                    : userInfoEntity1.attentions.toString(),
                            style: TextStyle(
                                color: Color(0xff0c0c0c),
                                fontSize: SizeUtil.px(32)),
                          ),
                          SizedBox(
                            height: SizeUtil.px(6),
                          ),
                          Text(
                            '关注',
                            style: TextStyle(
                                color: Color(0xff0c0c0c),
                                fontSize: SizeUtil.px(22)),
                          ),
                        ],
                      ),
                      SizedBox(
                        width: SizeUtil.px(60),
                      ),
                      Column(
                        children: [
                          Text(
                            userInfoEntity1 == null
                                ? '0'
                                : userInfoEntity1.fans == null
                                    ? '0'
                                    : userInfoEntity1.fans.toString(),
                            style: TextStyle(
                                color: Color(0xff0c0c0c),
                                fontSize: SizeUtil.px(32)),
                          ),
                          SizedBox(
                            height: SizeUtil.px(6),
                          ),
                          Text(
                            '粉丝',
                            style: TextStyle(
                                color: Color(0xff0c0c0c),
                                fontSize: SizeUtil.px(22)),
                          ),
                        ],
                      ),
                      // SizedBox(width: SizeUtil.px(60),),
                      // Column(
                      //   children: [
                      //     Text(userInfoEntity1 == null ? '0' : userInfoEntity1.follow.toString(),style: TextStyle(color: Color(0xff0c0c0c),fontSize: SizeUtil.px(32)),),
                      //     SizedBox(height: SizeUtil.px(6),),
                      //     Text('送礼',style: TextStyle(color: Color(0xff0c0c0c),fontSize: SizeUtil.px(22)),),
                      //   ],
                      // ),
                      // SizedBox(width: SizeUtil.px(60),),
                      // Column(
                      //   children: [
                      //     Text(userInfoEntity1 == null ? '1234156万' : userInfoEntity1.follow.toString(),style: TextStyle(color: Color(0xff0c0c0c),fontSize: SizeUtil.px(32)),),
                      //     SizedBox(height: SizeUtil.px(6),),
                      //     Text('收礼',style: TextStyle(color: Color(0xff0c0c0c),fontSize: SizeUtil.px(22)),),
                      //   ],
                      // ),
                    ],
                  ),
                  SizedBox(
                    height: SizeUtil.px(20),
                  ),
                  Divider(
                    height: SizeUtil.px(1),
                    color: Color(0xffbebebe),
                  ),
                  SizedBox(
                    height: SizeUtil.px(42),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      InkWell(
                        child: isFollowed
                            ? Text(
                                '已关注',
                                style: TextStyle(
                                    color: Color(0xff0c0c0c),
                                    fontSize: SizeUtil.px(22)),
                              )
                            : Text(
                                '关注',
                                style: TextStyle(
                                    color: Color(0xff0c0c0c),
                                    fontSize: SizeUtil.px(26)),
                              ),
                        onTap: () {
                          setState(() {
                            attentionAnchor().then((value) => (){
                              getRoomAnchor();
                              userInfoEntity1.attentions ++ ;
                          });
                          }

                          );
                        },
                      ),
                      SizedBox(
                        width: SizeUtil.px(121),
                      ),
                      InkWell(
                        child: Text(
                          '送礼',
                          style: TextStyle(
                              color: Color(0xff0c0c0c),
                              fontSize: SizeUtil.px(26)),
                        ),
                        onTap: () {
                          onGiftSettingTap();
                        },
                      ),
                      SizedBox(
                        width: SizeUtil.px(121),
                      ),
                      // InkWell(
                      //   child: Text(
                      //     '私信',
                      //     style: TextStyle(
                      //         color: Color(0xff0c0c0c),
                      //         fontSize: SizeUtil.px(26)),
                      //   ),
                      //   onTap: () {
                      //     Navigator.pushReplacement(
                      //       context,
                      //       new MaterialPageRoute(
                      //         builder: (context) => Conversion(
                      //           'c2c_' + userInfoEntity1.userId,
                      //           userId: userInfoEntity1.userId,
                      //         ),
                      //       ),
                      //     );
                      //   },
                      // )
                    ],
                  ),
                  SizedBox(
                    height: SizeUtil.px(39),
                  ),
                ],
              ),
            );
          }).then((_) => safeSetState(() {
            _popupGiftList = giftList;
            var timeout = Duration(seconds: 5);
            Timer(timeout, () {
              setState(() {
                _popupGiftList.clear();
              });
            });
          }));
    });
  }

  ///主播心愿单
  onWishSettingTap() {
    safeSetState(() {
      showModalBottomSheet(
          context: context,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(20),
              topRight: Radius.circular(20),
            ),
          ),
          builder: (BuildContext context) {
            return Container(
              color: Color(0xff140c3d),
              height: SizeUtil.px(985),
              child: Column(
                children: [
                  Container(
                    width: SizeUtil.px(714),
                    height: SizeUtil.px(246.74),
                    decoration: BoxDecoration(
                        image: DecorationImage(
                            image: AssetImage('assets/images/xinyuan.png'))),
                  )
                ],
              ),
            );
          }).then((_) => safeSetState(() {
            getRoomLeaderBoard();
            _popupGiftList = giftList;
            var timeout = Duration(seconds: 5);
            Timer(timeout, () {
              setState(() {
                _popupGiftList.clear();
              });
            });
          }));
    });
  }

  ///音乐设置
  onMusicSettingTap() {
    safeSetState(() {
      isShowMusicSetting = true;
      showModalBottomSheet<void>(
        context: context,
        isScrollControlled: true,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20),
            topRight: Radius.circular(20),
          ),
        ),
        builder: (BuildContext context) {
          return MusicSetting(
            playMusicTips: musicTips,
            onSelectMusice: (path, _musicTips) {
              audioEffectManager
                  .startPlayMusic(AudioMusicParam(id: 0, path: path));
              setState(() {
                musicTips = _musicTips;
              });
            },
            onAllMusicVolumeChange: (value) {
              audioEffectManager.setAllMusicVolume(value.toInt());
            },
            onMusicPitchChange: (value) {
              audioEffectManager.setMusicPitch(value.toInt(), 0);
            },
            onVoiceVolumeChange: (value) {
              audioEffectManager.setVoiceCaptureVolume(value.toInt());
            },
            onVoiceChangerTypeChange: (int type) {
              audioEffectManager.setVoiceChangerType(type);
            },
            onVoiceReverbTypeChange: (int type) {
              audioEffectManager.setVoiceReverbType(type);
            },
            onClose: () {
              safeSetState(() {
                isShowMusicSetting = false;
              });
              Navigator.of(context).pop(true);
            },
          );
        },
      );
    });
  }

  //显示pk列表
  onShowPkUserList() {
    getPKList(_currentLoginUser, () {
      showModalBottomSheet<void>(
        context: context,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20),
            topRight: Radius.circular(20),
          ),
        ),
        builder: (BuildContext context) {
          return PKUserList(
            roomList: _pkUserList,
            onRequestRoomPK: (roomId, ownerId) async {
              await trtcLiveCloud.requestRoomPK(roomId, ownerId);
              TxUtils.showToast("已发起PK邀请，等待同意", context);
              Navigator.of(context).pop(true);
            },
          );
        },
      );
    });
    safeSetState(() {
      isShowPkUserList = true;
    });
  }

  onRequestJoinAnchor() {
    safeSetState(() {
      isJoinAnchor = true;
    });
    trtcLiveCloud.requestJoinAnchor();
    TxUtils.showToast("等待主播接受.....", context);
  }

  onLikeTap() {
    trtcLiveCloud.sendRoomCustomMsg("like", _currentLoginUser);
    safeSetState(() {
      isFavoriteVisiable = true;
      _popupMessageList.add(userInfoEntity.nickname == ''
          ? '暂未设置昵称'
          : userInfoEntity.nickname + "点赞");
    });
    Future.delayed(Duration(seconds: 3), () {
      safeSetState(() {
        isFavoriteVisiable = false;
      });
    });
  }

  ///顶部按钮区域
  Widget getTopBtnList() {
    List<Widget> btnList = (isPKing && pkUserId != '')
        ? [
            LiveTextButton(
              text: "结束PK",
              onPressed: onCloseRoomTap,
              backgroundColor: Colors.red,
            )
          ]
        : [
            leaderList == null
                ? Container(
                    width: 0,
                    height: 0,
                  )
                : leaderList.length >= 1
                    ? Container(
                        width: SizeUtil.px(64),
                        height: SizeUtil.px(64),
                        child: Stack(
                          children: [
                            CircleAvatar(
                              backgroundImage: NetworkImage(
                                  'http://119.28.131.94:82' +
                                      leaderList[0].avatar),
                              radius: 16,
                            ),
                            Align(
                              alignment: Alignment.bottomCenter,
                              child: Container(
                                width: SizeUtil.px(56),
                                height: SizeUtil.px(21),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.all(
                                      Radius.circular(SizeUtil.px(28))),
                                  gradient: LinearGradient(
                                    begin: Alignment.topCenter,
                                    end: Alignment.bottomCenter,
                                    colors: [
                                      Color(0x80fea84a),
                                      Color(0x80f4840c)
                                    ],
                                  ),
                                ),
                                child: Center(
                                  child: Text(
                                    leaderList[0].gold,
                                    style: TextStyle(
                                        color: Color(0xffffffff),
                                        fontSize: SizeUtil.px(12)),
                                  ),
                                ),
                              ),
                            ),
                            Align(
                                alignment: Alignment.topRight,
                                child: Image.asset(
                                  'assets/images/gold_crown.png',
                                  width: SizeUtil.px(24),
                                  height: SizeUtil.px(24),
                                ))
                          ],
                        ),
                      )
                    : Container(
                        width: 0,
                        height: 0,
                      ),
            leaderList.length >= 2
                ? Container(
                    width: SizeUtil.px(64),
                    height: SizeUtil.px(64),
                    child: Stack(
                      children: [
                        CircleAvatar(
                          backgroundImage: NetworkImage(
                              'http://119.28.131.94:82' + leaderList[1].avatar),
                          radius: 16,
                        ),
                        Align(
                          alignment: Alignment.bottomCenter,
                          child: Container(
                            width: SizeUtil.px(56),
                            height: SizeUtil.px(21),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.all(
                                  Radius.circular(SizeUtil.px(28))),
                              gradient: LinearGradient(
                                begin: Alignment.topCenter,
                                end: Alignment.bottomCenter,
                                colors: [Color(0x80fea84a), Color(0x80f4840c)],
                              ),
                            ),
                            child: Center(
                              child: Text(
                                leaderList[1].gold,
                                style: TextStyle(
                                    color: Color(0xffffffff),
                                    fontSize: SizeUtil.px(12)),
                              ),
                            ),
                          ),
                        ),
                        Align(
                            alignment: Alignment.topRight,
                            child: Image.asset(
                              'assets/images/sliver_crown.png',
                              width: SizeUtil.px(24),
                              height: SizeUtil.px(24),
                            ))
                      ],
                    ),
                  )
                : Container(
                    width: 0,
                    height: 0,
                  ),
            leaderList.length >= 3
                ? Container(
                    width: SizeUtil.px(64),
                    height: SizeUtil.px(64),
                    child: Stack(
                      children: [
                        CircleAvatar(
                          backgroundImage: NetworkImage(
                              'http://119.28.131.94:82' + leaderList[2].avatar),
                          radius: 16,
                        ),
                        Align(
                          alignment: Alignment.bottomCenter,
                          child: Container(
                            width: SizeUtil.px(56),
                            height: SizeUtil.px(21),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.all(
                                  Radius.circular(SizeUtil.px(28))),
                              gradient: LinearGradient(
                                begin: Alignment.topCenter,
                                end: Alignment.bottomCenter,
                                colors: [Color(0x80fea84a), Color(0x80f4840c)],
                              ),
                            ),
                            child: Center(
                              child: Text(
                                leaderList[2].gold,
                                style: TextStyle(
                                    color: Color(0xffffffff),
                                    fontSize: SizeUtil.px(12)),
                              ),
                            ),
                          ),
                        ),
                        Align(
                            alignment: Alignment.topRight,
                            child: Image.asset(
                              'assets/images/copper_crown.png',
                              width: SizeUtil.px(24),
                              height: SizeUtil.px(24),
                            ))
                      ],
                    ),
                  )
                : Container(
                    width: 0,
                    height: 0,
                  ),
            Container(
              width: SizeUtil.px(83),
              height: SizeUtil.px(52),
              decoration: BoxDecoration(
                  color: Color(0x20f3f3f3),
                  borderRadius:
                      BorderRadius.all(Radius.circular(SizeUtil.px(25)))),
              child: Center(
                child: Text(
                  _onLineUserCount.toString(),
                  style: TextStyle(color: Color(0xffffffff)),
                ),
              ),
            ),
            // LiveImgButton(
            //   imgUrl: isBarrageON
            //       ? "assets/images/liveRoom/Barrage-ON.png"
            //       : "assets/images/liveRoom/Barrage.png",
            //   onTap: () {
            //     safeSetState(() {
            //       isBarrageON = !isBarrageON;
            //     });
            //   },
            // ),
            // 暂时不做share
            // LiveImgButton(
            //   imgUrl: "assets/images/liveRoom/share.png",
            //   onTap: () {},
            // ),
            LiveImgButton(
              imgUrl: "assets/images/liveRoom/closeRoom.png",
              onTap: () {
                onCloseRoomTap();
              },
            ),
          ];
    btnList.insert(
      0,
      Expanded(
        flex: 1,
        child: Container(
          padding: EdgeInsets.only(left: 0),
          margin: EdgeInsets.only(right: 70),
          decoration: new BoxDecoration(
            color: Color.fromRGBO(0, 0, 0, 0.2),
            borderRadius: BorderRadius.all(Radius.circular(26)),
          ),
          constraints: BoxConstraints(maxWidth: 180, minHeight: 48),
          width: 180,
          height: 48,
          child: Row(
            children: [
              InkWell(
                child: CircleAvatar(
                  radius: 32,
                  backgroundImage: NetworkImage(
                    userInfoEntity1 == null
                        ? 'https://imgcache.qq.com/operation/dianshi/other/5.ca48acfebc4dfb68c6c463c9f33e60cb8d7c9565.png'
                        : userInfoEntity1.avatar == ""
                            ? 'https://imgcache.qq.com/operation/dianshi/other/5.ca48acfebc4dfb68c6c463c9f33e60cb8d7c9565.png'
                            : "http://119.28.131.94:82" +
                                userInfoEntity1.avatar,
                  ),
                ),

                ///头像点击事件
                onTap: () {
                  onAvatarSettingTap();
                },
              ),
              Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Container(
                        height: 6,
                        width: 6,
                        color: Colors.red,
                      ),
                      Padding(
                          padding: EdgeInsets.only(left: 5),
                          child: Container(
                            constraints: BoxConstraints(maxWidth: 70),
                            child: Text(
                              _currenRoomName == ''
                                  ? userInfoEntity1 == null
                                      ? ''
                                      : userInfoEntity1.nickname + "的房间"
                                  : _currenRoomName,
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(color: Colors.white),
                            ),
                          )),
                    ],
                  ),
                  Container(
                    constraints: BoxConstraints(maxWidth: 80),
                    child: Text(
                      // _onLineUserCount.toString() + '人正在观看',
                      userInfoEntity1 == null
                          ? 'ID:' + '67863699'
                          : 'ID:' + userInfoEntity1.idNumber,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: Colors.white),
                    ),
                  )
                ],
              ),
            ],
          ),
        ),
      ),
    );
    return Container(
        margin: EdgeInsets.only(top: 35, left: 20, right: 10),
        child: Row(
          children: btnList,
        ));
  }

  ///聊天框
  Widget getInputMessage() {
    return Row(
      children: [
        Container(
          child: LiveImgButton(
              onTap: () {
                safeSetState(() {
                  isBarrageSliderOn = !isBarrageSliderOn;
                });
              },
              imgUrl: isBarrageSliderOn
                  ? "assets/images/liveRoom/barrage_slider_on.png"
                  : "assets/images/liveRoom/barrage_slider_off.png"),
        ),
        Expanded(
          flex: 2,
          child: TextField(
            cursorHeight: 25,
            controller: inputController,
            focusNode: inputFocusNode,
            onSubmitted: (s) {
              onSubmitted(s, context);
            },
            onChanged: (value) {
              inputController.text = value;
              inputController.selection = TextSelection.fromPosition(
                TextPosition(
                    affinity: TextAffinity.downstream, offset: value.length),
              );
            },
            autofocus: true,
            autocorrect: false,
            textAlign: TextAlign.left,
            keyboardType: TextInputType.multiline,
            textInputAction: TextInputAction.send,
            cursorColor: Color(0x006fff),
            decoration: InputDecoration(
              border: InputBorder.none,
              isCollapsed: true,
              isDense: true,
              hintText: "和大家说点什么吧…",
              contentPadding: EdgeInsets.only(
                top: 0,
                bottom: 5,
              ),
            ),
            style: TextStyle(fontSize: 16, color: Colors.white70),
            minLines: 1,
          ),
        ),
        LiveTextButton(
            text: "发送",
            onPressed: () {
              onSubmitted(inputController.text, context);
            }),
      ],
    );
  }

  //底部按钮列表
  Widget getBottomBtnList() {
    List<Widget> btnList = [];
    if (widget.isAdmin) {
      btnList = [
        Padding(padding: EdgeInsets.only(top: 8),
          child:
          InkWell(
            child: Container(
              width: 120,
              height: 30,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(30)),
                color: Color(0x20ffffff),
              ),
              child: Padding(
                padding: EdgeInsets.only(left: 10),
                child: Text('说些什么...',style: TextStyle(color: Color(0xffffffff),fontSize: 16),),
              ),
            ),
            onTap: (){
              onCommentTap();
            },
          ),
        ),
        // LiveImgButton(
        //   imgUrl: "assets/images/liveRoom/Comment.png",
        //   imgSize: 35,
        //   onTap: () {
        //     onCommentTap();
        //   },
        // ),
        Expanded(
          flex: 1,
          child: Container(
            child: Container(),
          ),
        ),
        LiveImgButton(
          imgUrl: "assets/images/liveRoom/CameraSwitch.png",
          imgSize: 35,
          onTap: () {
            onCameraSwitchTap();
          },
        ),
        // LiveImgButton(
        //   imgUrl: "assets/images/liveRoom/PK.png",
        //   imgSize: 52,
        //   onTap: () {
        //     onShowPkUserList();
        //   },
        // ),
        LiveImgButton(
          imgUrl: "assets/images/liveRoom/Filter.png",
          imgSize: 35,
          onTap: () {
            onFilterSettingTap();
          },
        ),
        //送礼物
        LiveImgButton(
          imgUrl: "assets/images/liveRoom/gift_icon.png",
          imgSize: 35,
          onTap: () {
            // onMusicSettingTap();
            onGiftSettingTap().then((_) => setState(() {
                  _popupGiftList = giftList;
                }));
          },
        ),
        LiveImgButton(
          imgUrl: "assets/images/chong.png",
          imgSize: 35,
          onTap: () {
            Navigator.of(context)
                .push(MaterialPageRoute(builder: (context) => WalletPage()));
          },
        ),
      ];
    } else {
      btnList = [
        // LiveImgButton(
        //   imgUrl: "assets/images/liveRoom/Comment.png",
        //   imgSize: 35,
        //   onTap: () {
        //     onCommentTap();
        //   },
        // ),
        Padding(padding: EdgeInsets.only(top: 8),
          child:
          InkWell(
            child: Container(
              width: 120,
              height: 30,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(30)),
                color: Color(0x20ffffff),
              ),
              child: Padding(
                padding: EdgeInsets.only(left: 10),
                child: Text('说些什么...',style: TextStyle(color: Color(0xffffffff),fontSize: 16),),
              ),
            ),
            onTap: (){
              onCommentTap();
            },
          ),
        ),
        Expanded(
          flex: 1,
          child: Container(
            child: Container(),
          ),
        ),
        //送礼物
        LiveImgButton(
          imgUrl: "assets/images/liveRoom/gift_icon.png",
          imgSize: 35,
          onTap: () {
            // onMusicSettingTap();
            onGiftSettingTap().then((_) => setState(() {
                  _popupGiftList = giftList;
                }));
          },
        ),
        LiveImgButton(
          imgUrl: "assets/images/chong.png",
          imgSize: 35,
          onTap: () {
            Navigator.of(context)
                .push(MaterialPageRoute(builder: (context) => WalletPage()));
          },
        ),
        // LiveImgButton(
        //   imgUrl: isJoinAnchor
        //       ? "assets/images/liveRoom/Microphone-off.png"
        //       : "assets/images/liveRoom/Microphone-on.png",
        //   imgSize: 35,
        //   onTap: () async {
        //     if (!isJoinAnchor) {
        //       onRequestJoinAnchor();
        //     } else {
        //       //主动退出主播
        //       safeSetState(() {
        //         isJoinAnchor = false;
        //         if (_smallVideoUserId.containsKey(_currentLoginUser))
        //           _smallVideoUserId.remove(_currentLoginUser);
        //       });
        //       await trtcLiveCloud.stopPublish();
        //     }
        //   },
        // ),

        ///屏蔽礼物、评论、礼物声音
        LiveImgButton(
          imgUrl: isShield
              ? "assets/images/liveRoom/music/no_select_hover.png"
              : "assets/images/liveRoom/music/no_select_normal.png",
          imgSize: 35,
          onTap: () async {
            if (isShield) {
              setState(() {
                isShield = false;
              });
              TxUtils.showToast('已解除屏蔽', context);
            } else {
              setState(() {
                isShield = true;
              });
              TxUtils.showToast('已屏蔽礼物、声音特效和消息', context);
            }
          },
        ),
        // LiveImgButton(
        //   imgUrl: "assets/images/liveRoom/Like.png",
        //   imgSize: 52,
        //   onTap: () {
        //     onLikeTap();
        //   },
        // ),
      ];
    }
    return Container(
      margin: EdgeInsets.only(bottom: 15),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisSize: MainAxisSize.max,
        children: btnList,
      ),
    );
  }

  ///发送消息
  onSubmitted(String messageVal, context) async {
    if (messageVal == '') {
      return;
    }
    if (isBarrageSliderOn) {
      trtcLiveCloud.sendRoomCustomMsg("slider", messageVal);
      safeSetState(() {
        _popupMessageList.add(messageVal);
      });
    } else {
      trtcLiveCloud.sendRoomTextMsg(messageVal);
    }
    addMessageLog(
      [MessageColor("我: ", Color(0xFFFC6091)), MessageColor(messageVal, null)],
    );
    TxUtils.showToast("发送成功", context);
    inputController.clear();
    safeSetState(() {
      isShowComment = false;
    });
  }

  Widget getPKingView() {
    return Container(
        color: Color.fromRGBO(0, 0, 0, 0.3),
        padding: EdgeInsets.only(top: 90),
        child: SizedBox(
          height: 350,
          child: Row(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                width: 180,
                height: 250,
                //color: Color.fromRGBO(0, 00, 0, 0.2),
                child: TRTCCloudVideoView(
                  key: ValueKey("PKPreview_VideoViewId"),
                  viewType: TRTCCloudDef.TRTC_VideoView_SurfaceView,
                  onViewCreated: (viewId) async {
                    trtcLiveCloud.stopCameraPreview();
                    trtcLiveCloud.startCameraPreview(isFrontCamera, viewId);
                  },
                ),
              ),
              Container(
                // color: Color.fromRGBO(0, 00, 0, 0.2),
                width: 180,
                height: 250,
                child: pkUserId != ''
                    ? TRTCCloudVideoView(
                        key: ValueKey("PKPlay_VideoViewId"),
                        viewType: TRTCCloudDef.TRTC_VideoView_SurfaceView,
                        onViewCreated: (viewId) async {
                          trtcLiveCloud.startPlay(pkUserId, viewId);
                        },
                      )
                    : Container(),
              ),
            ],
          ),
        ));
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
        child: WillPopScope(
      onWillPop: () {
        onCloseRoomTap();
      },
      child: Scaffold(
        body: GestureDetector(
          behavior: HitTestBehavior.translucent,
          onTap: () {
            if (inputFocusNode.hasFocus) {
              safeSetState(() {
                isShowComment = false;
              });
              inputFocusNode.unfocus();
            }
          },
          child: Stack(
            fit: StackFit.expand,
            children: [
              isPKing
                  ? getPKingView()
                  : Container(
                      color: Color.fromRGBO(0, 0, 0, 0.3),
                      child: Container(
                        child: !widget.isAdmin && !isOwerAvailable
                            ? Center(
                                child: Text(
                                  '直播暂不在线~~',
                                  style: TextStyle(
                                      fontSize: 18,
                                      color: Colors.white,
                                      fontWeight: FontWeight.bold),
                                ),
                              )
                            : TRTCCloudVideoView(
                                key: ValueKey("LiveRoomPage_bigVideoViewId"),
                                viewType:
                                    TRTCCloudDef.TRTC_VideoView_SurfaceView,
                                onViewCreated: (viewId) async {
                                  if (widget.isAdmin) {
                                    await trtcLiveCloud.stopCameraPreview();
                                    //为啥需要延迟，不延迟视频渲染会有问题。
                                    Future.delayed(Duration(milliseconds: 500),
                                        () async {
                                      await trtcLiveCloud.startCameraPreview(
                                          isFrontCamera, viewId);
                                    });
                                  } else {
                                    await trtcLiveCloud.startPlay(
                                        _currentOwnerId, viewId);
                                  }
                                },
                              ),
                      ),
                    ),
              Align(
                alignment: Alignment.topLeft,
                child: getTopBtnList(),
              ),
              Padding(
                padding: EdgeInsets.only(top: SizeUtil.px(173)),
                child: Align(
                  alignment: Alignment.topCenter,
                  child: Container(
                      width: SizeUtil.px(159),
                      height: SizeUtil.px(35),
                      decoration: BoxDecoration(
                          color: Color(0x16ffffff),
                          borderRadius: BorderRadius.all(
                              Radius.circular(SizeUtil.px(44)))),
                      child: InkWell(
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Image.asset(
                              'assets/images/sofa.png',
                              width: SizeUtil.px(68.37),
                              height: SizeUtil.px(27.42),
                            ),
                            SizedBox(
                              width: SizeUtil.px(6),
                            ),
                            Text(
                              '抢头条',
                              style: TextStyle(
                                  color: Color(0xfffffffd),
                                  fontSize: SizeUtil.px(21)),
                            )
                          ],
                        ),
                        onTap: () {
                          print('抢头条');
                        },
                      )),
                ),
              ),
              Padding(
                padding: EdgeInsets.only(top: SizeUtil.px(168)),
                child: Align(
                    alignment: Alignment.topRight,
                    child: InkWell(
                      child: Container(
                        width: SizeUtil.px(120),
                        height: SizeUtil.px(43),
                        child: Stack(
                          children: [
                            Padding(
                              padding: EdgeInsets.only(
                                  top: SizeUtil.px(2), right: SizeUtil.px(32)),
                              child: Align(
                                alignment: Alignment.topRight,
                                child: Container(
                                  width: SizeUtil.px(93),
                                  height: SizeUtil.px(41),
                                  decoration: BoxDecoration(
                                      color: Color(0x16ffffff),
                                      borderRadius: BorderRadius.all(
                                          Radius.circular(SizeUtil.px(25)))),
                                  child: Row(
                                    children: [
                                      Padding(
                                        padding: EdgeInsets.only(
                                            left: SizeUtil.px(15)),
                                        child: Text(
                                          '心愿',
                                          style: TextStyle(
                                              color: Color(0xfff3f3f3),
                                              fontSize: SizeUtil.px(21)),
                                        ),
                                      )
                                    ],
                                  ),
                                ),
                              ),
                            ),
                            Align(
                              alignment: Alignment.topRight,
                              child: Padding(
                                padding: EdgeInsets.only(
                                    top: SizeUtil.px(0),
                                    right: SizeUtil.px(15)),
                                child: Image.asset(
                                  'assets/images/heart.png',
                                  width: SizeUtil.px(49),
                                  height: SizeUtil.px(43),
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      onTap: () {
                        onWishSettingTap();
                      },
                    )),
              ),
              isShield
                  ? Container(
                      width: 0,
                      height: 0,
                    )
                  : Align(
                      alignment: Alignment.topLeft,
                      child: Padding(
                        padding: EdgeInsets.only(
                            left: SizeUtil.px(15), top: SizeUtil.px(300)),
                        child: ListView.builder(
                            itemCount: _popupGiftList.length,
                            controller: _scrollController,
                            shrinkWrap: true,
                            itemBuilder: (context, index) {
                              return GiftList(
                                giftEntity: GiftEntity.fromJson(
                                  jsonDecode(_popupGiftList[index]),
                                ),
                                userInfoEntity: userInfoEntity2,
                              );
                            }),
                      ),
                    ),
              isShield
                  ? Container(
                      width: 0,
                      height: 0,
                    )
                  : PopUpMessageList(
                      popupMessageList: isBarrageON ? _popupMessageList : [],
                    ),
              isShield
                  ? Container(
                      width: 0,
                      height: 0,
                    )
                  : LiveMessageList(
                      messageList: _messageLogList,
                    ),
              SubVideoList(
                isShowClose: widget.isAdmin ? true : false,
                userList: (pkUserId != "" && isPKing)
                    ? []
                    : _smallVideoUserId.keys.toList(),
                onClose: (String userId) async {
                  if (userId == _currentLoginUser) {
                    //主动下麦
                    await trtcLiveCloud.stopPublish();
                    setState(() {
                      isJoinAnchor = false;
                    });
                  } else {
                    await trtcLiveCloud.kickoutJoinAnchor(userId);
                  }

                  if (_smallVideoUserId.containsKey(userId))
                    safeSetState(() {
                      _smallVideoUserId.remove(userId);
                    });
                },
                onViewCreate: (userId, viewId) async {
                  String currLoginUserId = await TxUtils.getLoginUserId();
                  if (userId == currLoginUserId) {
                    trtcLiveCloud.startCameraPreview(isFrontCamera, viewId);
                    return;
                  }
                  trtcLiveCloud.startPlay(userId, viewId);
                },
              ),
              FavoriteAnimation(isVisible: isFavoriteVisiable),
              Positioned(
                bottom: 10,
                left: 10,
                right: 10,
                child: isShowComment ? getInputMessage() : getBottomBtnList(),
              ),
              widget.isAdmin
                  ? Padding(
                      padding: EdgeInsets.only(top: SizeUtil.px(246)),
                      child: Align(
                        alignment: Alignment.topRight,
                        child: Container(
                          width: SizeUtil.px(98.62),
                          height: SizeUtil.px(88.83),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.only(
                                topLeft: Radius.circular(SizeUtil.px(34)),
                                bottomLeft: Radius.circular(SizeUtil.px(34))),
                            gradient: LinearGradient(
                              begin: Alignment.centerLeft,
                              end: Alignment.centerRight,
                              colors: [Color(0xffff0865), Color(0xfffe7b71)],
                            ),
                          ),
                          child: InkWell(
                            child: Center(
                              child: Text(
                                'PK',
                                style: TextStyle(
                                    color: Color(0xfff3f3f3),
                                    fontSize: SizeUtil.px(48),
                                    fontWeight: FontWeight.bold),
                              ),
                            ),
                            onTap: () {
                              onShowPkUserList();
                            },
                          ),
                        ),
                      ),
                    )
                  : Container(
                      width: 0,
                      height: 0,
                    ),
            ],
          ),
        ),
      ),
    ));
  }

  ///下播
  Future<void> endBroadcast() async {
    Alert.showCustomDialog(
        context: context,
        title: '直播提示',
        message: '您是否要退出当前直播间',
        certainPressed: () async {
          SharedPreferences prefs = await SharedPreferences.getInstance();
          String appToken = prefs.getString('app-token');
          BaseRequest request = EndBroadcast();
          request.addHeader('usertoken', appToken);
          var result = await HiNet.getInstance().fire(request);
          if (result['code'] == 0) {
            TxUtils.showToast('下播成功', context);
            // Navigator.pop(context);
            stopAndGoIndex();
          } else if (result['code'] == -1) {
            TxUtils.showErrorToast('登录失效，请重新登录', context);
            Navigator.pop(context);
            Navigator.of(context).push(MaterialPageRoute(
              builder: (context) {
                return LoginPage(
                  arguments: {'loginCode': '-1'},
                );
              },
            ));
          } else {
            TxUtils.showToast(result['message'], context);
          }
        });
  }

  Future<void> liveDropOut() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    Alert.showCustomDialog(
        context: context,
        title: '直播提示',
        message: '您是否要退出当前直播间',
        certainPressed: () async {
          BaseRequest request = LiveDropOutRequest();
          request
              .add('room_id', _currentRoomId)
              .addHeader('usertoken', appToken);
          var result = await HiNet.getInstance().fire(request);
          if (result['code'] == 0) {
            TxUtils.showToast('退出成功', context);
            // Navigator.pop(context);
            stopAndGoIndex();
          } else if (result['code'] == -1) {
            TxUtils.showErrorToast('登录失效，请重新登录', context);
            Navigator.pop(context);
            Navigator.of(context).push(MaterialPageRoute(
              builder: (context) {
                return LoginPage(
                  arguments: {'loginCode': '-1'},
                );
              },
            ));
          } else {
            TxUtils.showToast(result['message'], context);
          }
        });
  }

  ///获取房间内主播信息
  getRoomAnchor() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = GetRoomAnchorRequest();
    request.add('room_id', _currentRoomId).addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == 0) {
      setState(() {
        userInfoEntity1 = UserInfoEntity.fromJson(
            new Map<String, dynamic>.from(result['data']));
        isAttention();
      });
    } else if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(
            arguments: {'loginCode': '-1'},
          );
        },
      ));
    } else {
      TxUtils.showToast(result['message'], context);
    }
  }

  ///关注主播
  Future<void> attentionAnchor() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = AttentionRoomRequest();
    request
        .add('user_id', userInfoEntity1.userId1)
        .add('type', 2)
        .addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == 0) {
      TxUtils.showToast(result['data'], context);
      setState(() {
        isFollowed = true;
      });
    } else if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(
            arguments: {'loginCode': '-1'},
          );
        },
      ));
    } else {
      TxUtils.showToast(result['message'], context);
    }
  }

  ///获取房间内排行榜
  Future<void> getRoomLeaderBoard() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = RoomLeaderBoardRequest();
    request
        .add('room_id', _currentRoomId)
        .add('type', 1)
        .addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == 0) {
      List<Map<String, dynamic>> listMap =
          new List<Map<String, dynamic>>.from(result['data']);
      List<LeaderBorardEntity> leader = [];
      for (int i = 0; i < listMap.length; i++) {
        leader.add(LeaderBorardEntity.fromJson(listMap[i]));
        int gold = int.parse(leader[i].gold);
        leader[i].gold = (gold / 10000).toString() + "万";
      }
      setState(() {
        leaderList = leader;
      });
    } else if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(
            arguments: {'loginCode': '-1'},
          );
        },
      ));
    } else {
      TxUtils.showToast(result['message'], context);
    }
  }

  ///是否关注主播
  isAttention() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String appToken = prefs.getString('app-token');
    BaseRequest request = AttentionAnchorRequest();
    request
        .add('anchor_id', userInfoEntity1.userId1)
        .addHeader('usertoken', appToken);
    var result = await HiNet.getInstance().fire(request);
    if (result['code'] == 0) {
      setState(() {
        isFollowed = result['data'];
      });
    } else if (result['code'] == -1) {
      TxUtils.showErrorToast('登录失效，请重新登录', context);
      Navigator.pop(context);
      Navigator.of(context).push(MaterialPageRoute(
        builder: (context) {
          return LoginPage(
            arguments: {'loginCode': '-1'},
          );
        },
      ));
    } else {
      TxUtils.showToast(result['message'], context);
    }
  }

  getLocation() async {
    Location location = new Location();
    bool _serviceEnabled;
    PermissionStatus _permissionGranted;
    LocationData _locationData;
    _serviceEnabled = await location.serviceEnabled();
    if (!_serviceEnabled) {
      _serviceEnabled = await location.requestService();
      if (!_serviceEnabled) {
        return;
      }
    }
    _permissionGranted = await location.hasPermission();
    if (_permissionGranted == PermissionStatus.DENIED) {
      _permissionGranted = await location.requestPermission();
      if (_permissionGranted != PermissionStatus.GRANTED) {
        return;
      }
    }
    _locationData = await location.getLocation();
    print('123213' + _locationData.toString());
  }
}
